package com.jason.quectel0805.activities;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import com.jason.quectel0805.R;
import com.jason.quectel0805.services.DownloadService;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

/**
 * @author：Jason
 * @date: 2022/8/10 16:35
 * @email：1129847330@qq.com
 * @description: 下载文件：
 * 1、创建service，在后台默默地下载
 * 2、service里面创建一个子线程下载
 * 3、使用okhttp
 * 4、使用IO操作将文件写入到SDCard DOWNLOAD目录当中
 */
public class DownloadFileActivity extends AppCompatActivity {
    public static final String FILE_URL = "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimage.xny365.com%2Fauto%2F202001%2F5sq5n5ave1v" +
            ".jpg&refer=http%3A%2F%2Fimage.xny365.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1662712472&t=45212117b77d82ec1a6abd881227392e";

    private String downloadUrl = FILE_URL;

    //所有声明周期方法都是由Framework调用的，应用层负责重写实现自己的逻辑
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_download_file);
        Intent intent = getIntent();
        downloadUrl = intent.getStringExtra("download_url");
    }

    public void downloadFile(View view) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                startDownloadService();
            } else {
                //    没有权限，那就申请权限
                requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 100);
            }
        }
    }

    private void startDownloadService() {
        Intent intent = new Intent(this, DownloadService.class);
        intent.putExtra("download_url", FILE_URL);
        startService(intent);
    }

    /**
     * 权限申请回调
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 100 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(this, "授权成功", Toast.LENGTH_SHORT).show();
            startDownloadService();
        } else {
            Toast.makeText(this, "授权失败", Toast.LENGTH_SHORT).show();
        }
    }
}